import React, { Component } from 'react';
import { ChromePicker } from 'react-color';
import onClickOutside from 'react-onclickoutside';

class ColorPicker extends Component {
  static defaultProps = {
    value: 'rgba(0,0,0,1)',
    onChange: () => {},
  };

  constructor(props) {
    super(props);
    this.state = {
      displayColorPicker: false,
      color: props.value || props.defaultValue,
    };
  }

  handleClick = () => {
    this.setState({ displayColorPicker: !this.state.displayColorPicker });
  };

  handleChange = color => {
    const { r, g, b, a } = color.rgb;
    const value = `rgba(${r},${g},${b},${a})`;
    this.setState({ color: value });
    this.props.onChange(value);
  };

  handleClickOutside = e => {
    this.setState({ displayColorPicker: false });
  };

  render() {
    return (
      <div className="color-picker" style={this.props.style}>
        <div style={styles.swatch} onClick={this.handleClick}>
          <div style={{ ...styles.color, background: this.state.color }} />
        </div>
        {this.state.displayColorPicker ? (
          <div style={styles.popover}>
            <ChromePicker
              color={this.state.color}
              onChange={this.handleChange}
            />
          </div>
        ) : null}
      </div>
    );
  }

  // rgba(1,2,3,0) ==> ['1','2','3','0'] => {r,g,b,a}
  getColor = string => {
    const reg = /^rgba\([\d|,]+\)$/;
    if (!string.test(reg)) {
      console.warn('不是rgba格式,不能转换');
      return {};
    }
    const values = string.slice(5, -1).split(',');
    return {
      r: values[0],
      g: values[1],
      b: values[2],
      a: values[3],
    };
  };
}

const styles = {
  color: {
    height: 18,
    width: 18,
  },
  swatch: {
    background:
      'url() center left',
    borderRadius: 1,
    boxShadow: '0 0 0 1px rgba(0,0,0,.1)',
    display: 'inline-block',
    cursor: 'pointer',
    position: 'relative',
    width: '100%',
  },
  popover: {
    position: 'absolute',
    zIndex: 10,
  },
};

export default onClickOutside(ColorPicker);
